from werkzeug.utils import redirect
from util.captcha.captcha import captcha
from views.base import BaseHandler
from util.sms_code import send_message
import re,random,requests
from util.myredis import r
from db.datab import db
from util.myjwt import myjwt
import json,time

class UserHandler(BaseHandler):
    def get(self):
        # 获取code
        code = self.get_query_argument('code')
        # 向access_token接口发送post请求
        data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
                "grant_type": "authorization_code",
                'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
        res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
        # print(res.text)
        mes = json.loads(res.text)
        # print(mes['uid'])
        # 获取token和uid
        uid = mes['uid']
        token = mes['access_token']
        # 查询此uid是否存在
        sql = "select u.id,u.mobile from user as u inner join sf_login as sl on u.id=sl.userid where sl.uid='%s'"%(uid)
        user = db.findOne(sql)
        if user:
            token = myjwt.jwt_en(
                data={"data": {"uid": user['id'], "mobile": user['mobile'], 'exp': int(time.time())}})
            self.redirect("http://localhost:8080/open?token=" + token + "&userid=" + str(user['id']))

        else:
            # 绑定
            self.redirect("http://localhost:8080/wbzz?token=" + str(token) + "&uid=" + str(uid))

class getWBurlHandler(BaseHandler):
    def get(self):
        client_id = "3674019597"
        redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
        url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
            client_id, redirect_uri)
        self.finish({'code':200,'url':url})


class bindMHandler(BaseHandler):
    def post(self):
        # 接收参数
        data = json.loads(self.request.body)
        # 加入用户表
        sql = "insert into user(mobile) values('%s')"%(data['mobile'])
        userid = db.update(sql)
        uid = data['uid']
        token = data['token']
        # 加入三方登录表
        sql1 = "insert into sf_login(userid,webfrom,uid,token) values(%d,'weibo','%s','%s')"%(userid,int(uid),token)
        db.update(sql1)
        db.commit()
        # 返回jwt token
        token = myjwt.jwt_en(data={"data": {"uid": userid, "mobile": data['mobile'], 'exp': int(time.time())}})
        self.finish({'code':200,'token':token,'userid':userid})

